package com.hanserwei.han_picture.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanserwei.han_picture.domain.common.ApiResponse;
import com.hanserwei.han_picture.websocket.message.AiProcessMessage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket测试控制器
 * 用于测试Long类型序列化和WebSocket消息格式
 *
 * @author hanserwei
 */
@RestController
@RequestMapping("/websocket-test")
@RequiredArgsConstructor
@Tag(name = "WebSocketTestController")
@Slf4j
public class WebSocketTestController {

    private final ObjectMapper objectMapper;

    @Operation(summary = "测试Long类型序列化")
    @GetMapping("/test-long-serialization")
    public ApiResponse<Map<String, Object>> testLongSerialization(
            @RequestParam(defaultValue = "1234567890123456789") Long testId) {
        
        try {
            // 创建测试消息
            AiProcessMessage message = AiProcessMessage.createSuccessMessage(
                testId, 
                testId + 1, 
                "测试标题", 
                "测试分类", 
                Arrays.asList("标签1", "标签2", "标签3")
            );
            
            // 使用ObjectMapper序列化（WebSocket方式）
            String webSocketJson = objectMapper.writeValueAsString(message);
            
            Map<String, Object> result = new HashMap<>();
            result.put("originalPictureId", testId);
            result.put("originalUserId", testId + 1);
            result.put("webSocketSerializedJson", webSocketJson);
            
            // 验证WebSocket序列化是否包含引号（字符串格式）
            boolean wsPictureIdAsString = webSocketJson.contains("\"pictureId\":\"" + testId + "\"");
            boolean wsUserIdAsString = webSocketJson.contains("\"userId\":\"" + (testId + 1) + "\"");
            
            result.put("webSocket_pictureIdAsString", wsPictureIdAsString);
            result.put("webSocket_userIdAsString", wsUserIdAsString);
            
            // 测试HTTP接口序列化（通过返回这个result，Spring MVC会序列化）
            result.put("httpTest_pictureId", testId);  // 这会被Spring MVC序列化
            result.put("httpTest_userId", testId + 1); // 这会被Spring MVC序列化
            
            if (wsPictureIdAsString && wsUserIdAsString) {
                result.put("webSocketStatus", "SUCCESS - WebSocket中Long类型正确序列化为字符串");
            } else {
                result.put("webSocketStatus", "FAILED - WebSocket中Long类型未正确序列化为字符串");
            }
            
            log.info("Long序列化测试 - 原始ID: {}, WebSocket序列化结果: {}", testId, webSocketJson);
            
            return ApiResponse.success("Long类型序列化测试完成", result);
            
        } catch (Exception e) {
            log.error("Long序列化测试失败", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", e.getMessage());
            return ApiResponse.success("测试失败: " + e.getMessage(), errorResult);
        }
    }

    @Operation(summary = "生成测试用的大Long值")
    @GetMapping("/generate-test-ids")
    public ApiResponse<Map<String, Object>> generateTestIds() {
        Map<String, Object> result = new HashMap<>();
        
        // JavaScript安全整数范围
        long jsMaxId = 9007199254740991L; // 2^53 - 1
        
        // 生成一些测试用的Long值
        long smallId = 123456789L;
        long overJsMaxId = jsMaxId + 1000L;
        long snowflakeId = System.currentTimeMillis() << 22 | (1L << 12) | 1L; // 模拟雪花算法ID
        
        result.put("smallId", smallId);
        result.put("jsMaxSafeInteger", jsMaxId);
        result.put("overJsMaxId", overJsMaxId);
        result.put("simulatedSnowflakeId", snowflakeId);
        result.put("jsMaxSafeIntegerInfo", "JavaScript最大安全整数: " + jsMaxId);
        result.put("warning", "超过JavaScript安全整数范围的Long值需要序列化为字符串");
        
        return ApiResponse.success("测试ID生成成功", result);
    }
}
